package com.cainiao.util;

import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by cfour on 16/7/11.
 */
public class StringUtil {

    public static String compilerClubStr = "s/<(script|object|ABBR|ACRONYM|ADDRESS|APPLET|AREA|BASE|BDO|BLOCKQUOTE|BODY|BUTTON|CODE|DIR|FIELDSET|FRAMESET|FORM|FRAME|FRAMESET|HEAD|HTML|IFRAME|INPUT|KBD|LEGEND|LINK|MAP|MENU|META|NOFRAMES|NOSCRIPT|OPTGROUP|OPTION|PARAM|SAMP|SELECT|SUB|SUP|TEXTAREA|TITLE|VAR|embed)/&lt;$1/ig";

    public static String compilerJs = "s/(onclick=|ondblclick=|onload=|onmousedown=|onmouseup=|onmouseover=|onmousemove=|onmouseout=|onkeypress=|onkeydown=|onkeyup=|onabort=|onbeforeunload=|onerror=|onmove=|onresize=|onscroll=|onstop=|onunload=|onblur=|onchange=|onfocus=|onreset=|onsubmit=|onbounce=|onfinish=|onstart=|onbeforecopy=|onbeforecut=|onbeforeeditfocus=|onbeforepaste=|onbeforeupdate=|oncontextmenu=|oncopy=|oncut=|ondrag=|ondragdrop=|ondragend=|ondragenter=|ondragleave=|ondragover=|ondragstart=|ondrop=|onlosecapture=|onpaste=|onselect=|onselectstart=|onafterupdate=|oncellchange=|ondataavailable=|ondatasetchanged=|ondatasetcomplete=|onerrorupdate=|onrowenter=|onrowexit=|onrowsdelete=|onrowsinserted=|onafterprint=|onbeforeprint=|onfilterchange=|onhelp=|onpropertychange=|onreadystatechange=)/$1awoo/ig";

    public static String compilerOnLoad = "s/(id=loadImg)/onload=\"imgOnLoad(this);\"/ig";

    public static String compilerCLASS = "s/(class)/&#99;lass/ig";

    public static String compilerID = "s/id=/&#105;d=/ig";

    public static String compilerBlogStr = "s/<(script|BODY|IFRAME)/&lt;$1/ig";

    public static String compilerImgStr = "s/<img\\s+[^>]>//ig";

    public static String removeUBBImgRegexp = "s/[img\\s+([^\\s]+)\\s+([^\\]]+)\\](https?:\\/\\/\\S+?)\\[\\/img\\]//isg";

    /**
     * 转成类似/u09ab格式的字符
     * @param base
     * @return
     */
    public static String stringToHex(String base){
        StringBuffer buffer = new StringBuffer();
        int intValue;
        for(int x = 0; x < base.length(); x++)
        {
            int cursor = 0;
            intValue = base.charAt(x);
            String binaryChar = new String(Integer.toBinaryString(base.charAt(x)));
            for(int i = 0; i < binaryChar.length(); i++)
            {
                if(binaryChar.charAt(i) == '1')
                {
                    cursor += 1;
                }
            }
            if((cursor % 2) > 0)
            {
                intValue += 128;
            }
            buffer.append("/u"+Integer.toHexString(intValue));
        }

        return buffer.toString();
    }

    public static double div(double v1, double v2, int scale) {
        if (scale < 0)
            scale = 0;
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 高亮关键字
     *
     * @param body
     * @param words
     * @return 返回的字符串长度不超过200
     * @throws UnsupportedEncodingException
     */
    public static String highlightWords(String body, String words)
            throws UnsupportedEncodingException {
        if (body == null || body.length() < 1) {
            return "";
        }

        if (words == null || words.length() < 1) {
            return body.substring(0, Math.min(200, body.length()));
        }

        String tmp;
        int pos = body.indexOf(words);
        if (pos > -1) {

            body = StringUtils.replace(body, words, "<font color=CC0033>"
                    + words + "</font>");

            tmp = body;
        } else {
            tmp = body.substring(0, Math.min(200, body.length()));
        }

        return tmp;
    }

    /**
     * 将html代码转换成页面可显示形式
     *
     * @param src
     * @return
     */
    public static String escapeHTML(String src) {
        if (StringUtils.isEmpty(src)) {
            return src;
        }

        src = StringUtils.replace(src, "<", "&lt;");
        src = StringUtils.replace(src, "\"", "&quot;");
        src = StringUtils.replace(src, "'", "&#39;");
        src = StringUtils.replace(src, "\"", "&#34;");
        src = StringUtils.replace(src, "&", "&#38;");
        return src;
    }

    public static String escapeJson(String src){
        if (StringUtils.isEmpty(src)) {
            return src;
        }

        src = StringUtils.replace(src, "\"", "&#34;");
        return src;
    }

    /**
     * 计算字条串的长度. 根据oracle的字符编码不同而不同. 如为UTF-8, 英文字符占用1个字节, 中文汉字或其它占用3个字节
     */
    public static int getLength(String s) {
        if (s == null)
            return 0;
        char ac[] = s.toCharArray();
        int i = 0;
        for (int j = 0; j < ac.length; j++)
            if (Character.UnicodeBlock.of(ac[j]) == Character.UnicodeBlock.BASIC_LATIN) {
                i++;
            } else {
                i += 3;
            }
        return i;
    }

    /**
     * 循环找出匹配内容
     */
    public static String matcherString(String str, String cp) {
        if (null == str) {
            return null;
        }
        // String resultString = str;

        Pattern p = Pattern.compile(cp, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(str);
        StringBuffer sb = new StringBuffer();
        boolean result = m.find();
        // 使用循环将句子里所有匹配的内容找出并替换再将内容加到sb里
        while (result) {
            sb.append(m.group());
            // sb.append(s);
            // 继续查找下一个匹配对象
            result = m.find();
        }
        // resultString =

        return String.valueOf(sb);
    }

    /*public static boolean isUrl(String url) {
        boolean a = Pattern.matches(
                "http://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?", url);
        if (a) {
            return true;
        }
        return false;
    }*/

    /**
     * 截取字符串, 在尾部加入新字符串
     *
     */
    public static String truncateNicely(String str, int lower, int upper,
                                        String appendToEnd) {

        if (StringUtils.isEmpty(str)) {
            return "";
        }

        if (upper < lower)
            upper = lower;
        if (str.length() > upper) {
            int loc = str.lastIndexOf(' ', upper);
            if (loc >= lower)
                str = str.substring(0, loc);
            else
                str = str.substring(0, upper);
            str = str + appendToEnd;
        }
        return str;
    }

    /**
     * 处理html, 去除字符"<"与">"之间的字符串(包括<>)
     *
     */
    public static String removeHtml(String str) {
        String regex = "<.*?>";
        return str.replaceAll(regex, "");
    }

    public static String removeNbsp(String str){
        String regex = "&nbsp;";
        return str.replaceAll(regex, "");
    }

    /**
     * 将系统换行符换成html换行符
     *
     * @param str
     * @return
     */
    public static String convertBreakLine(String str) {
        String regex = "\r\n";
        return str.replaceAll(regex, "<br>");
    }

    public static String clearBreakLine(String str){
        String regex = "\r\n";
        return str.replaceAll(regex, "");
    }

    public static String clearBr(String str){
        String regex = "<br>";
        return str.replaceAll(regex, "");
    }

    public static boolean isHaveFlashTag(String body) {
        Pattern pattern = Pattern.compile("\\[flash\\]http://",
                Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(body);
        return matcher.find();
    }

    public static boolean isHaveImgTag(String body) {
        Pattern pattern = Pattern
                .compile("\\[img\\]", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(body);
        return matcher.find();
    }




    /**
     * 支持正则表达式的subString
     *
     * 例子：
     * 抓取网页中的所有url（仅限于a标签内的链接）
     *
     * Pattern prePattern = Pattern.compile("<[aA][^>]*>");
     * Pattern op = Pattern.compile("(([Hh][rR][eE][fF]){1})(\\s*)=(\\s*)(['\"]?)");
     * Pattern cp = Pattern.compile("[(\\s)'\">]{1}");
     * return StringUtil.subStringBetween(page, prePattern, op, cp);
     *
     * @param str
     * @param preSelectPattern 预选取
     * @param op
     * @param cp
     * @return
     */
    public static List<String> subStringBetween(String str, Pattern preSelectPattern, Pattern op, Pattern cp){
        List<String> subStrList = new ArrayList<String>();


        //预选取
        List<String> preStrList = new ArrayList<String>();
        if(null != preSelectPattern){
            Matcher matcher = preSelectPattern.matcher(str);
            while (matcher.find()) {
                preStrList.add(preStrList.size(), matcher.group());
            }
        }else{
            preStrList.add(preStrList.size(), str);
        }



        for(String preStr : preStrList){
            Matcher opm = op.matcher(preStr);
            opm.find();
            int start = opm.end();

            String s = preStr.substring(start);
            Matcher cpm = cp.matcher(s);
            cpm.find();
            int end = cpm.start();

            s = s.substring(0, end);

            subStrList.add(s);
        }

        return subStrList;
    }

    public String replace(String text, String searchString, String replacement){
        return StringUtils.replace(text, searchString, replacement);
    }


    /**
     * 字符串ip转换为long
     * @param
     * @return
     */
    public static long stringIpToLong(String ip) {
        String[] ips = ip.split("[.]");
        long num =  16777216L*Long.parseLong(ips[0]) + 65536L*Long.parseLong(ips[1]) + 256*Long.parseLong(ips[2]) + Long.parseLong(ips[3]);
        return num;
    }

    /**
     * 长整型ip转换为string
     * @param
     * @return
     */
    public static String longIpToString(long ipLong) {

        long mask[] = {0x000000FF,0x0000FF00,0x00FF0000,0xFF000000};
        long num = 0;
        StringBuffer ipInfo = new StringBuffer();
        for(int i=0;i<4;i++){
            num = (ipLong & mask[i])>>(i*8);
            if(i>0) ipInfo.insert(0,".");
            ipInfo.insert(0,Long.toString(num,10));
        }
        return ipInfo.toString();
    }

    public static boolean sql_Injection(String str) {
        String inj_str = "' and exec insert select delete update"
                + " count * % chr mid master truncate char declare ; or - + ,";
        String arr[] = inj_str.split(" ");
        for (int i = 0; i < arr.length; i++) {
            if (str.indexOf(arr[i]) != -1) {
                return true;
            }
        }
        return false;
    }
    public static String dateFormat(Date date) {
        if(date == null ){
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

}
